package thread;

/**
 * @Author liangzai
 * @Description:
 */

class MyBlockQeueu{
    private int head = 0;

    private int tile = 0;

    private int size = 0;

    private String[] data = null;

    public MyBlockQeueu(int capacity){
        data = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (this) {
            while (size >= data.length) {
                this.wait();
            }

            data[tile] = elem;
            tile++;
            if (tile >= data.length) {
                tile = 0;
            }
            size++;
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }

            String elem = data[head];
            head++;
            if (head >= data.length) {
                head = 0;
            }
            size--;
            this.notify();
            return elem;
        }
    }
}

public class Demo1 {
    public static void main(String[] args) {
        MyBlockQeueu qeueu = new MyBlockQeueu(1000);

        Thread producer = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    qeueu.put(i+"");
                    System.out.println("生产元素:"+i+"");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"producer");

        Thread conumer = new Thread(()->{
            while(true) {
                try {
                    String elem = qeueu.take();
                    System.out.println("消费元素:"+elem);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"conumer");

        producer.start();
        conumer.start();
    }
}

























